{CACHE} = require('fckoa/db/redis')
PG = require('fckoa/db/pg')
assert = require('assert')
MONTH = 86400*30
SESSION_KEY = "I"
R = SESSION_KEY+"#"

TABLE_SESSION = 'auth.session'

module.exports = exports = {
    user_id : (I)->
        user_id = await CACHE.get(R+I)
        if user_id
            user_id = user_id - 0
            return user_id

    # destroy:(I)->
    #     console.log "delete", I
    #     @sessions.delete I
    bind:(user_id, I)->
        if user_id
            assert(I.length==24)
            await PG.raw(
                """INSERT INTO auth.session (user_id,"I") VALUES (?,?)  ON CONFLICT ("I") DO UPDATE SET user_id=EXCLUDED.user_id"""
                [
                    user_id
                    I
                ]
            )
            await CACHE.setex(R+I, MONTH, user_id)

    logout:(user_id)->
        cache = CACHE.pipeline()
        for i in await PG.rows(
            """SELECT "I" FROM #{TABLE_SESSION} WHERE user_id=?"""
            user_id
        )
            cache.del(R+i.I)
        await cache.exec()
        await PG(TABLE_SESSION).where({user_id}).delete()
}
